<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var numIslands = function (grid) {
                //遍历grid，如果遇到1就sum++，推入队列，而且让其标记为0，避免重复，然后bfs遍历四周，
                //如果越界或者为0，那么就直接跳过，如果遇到了1，那么就再次置0，推入队列，继续dfs它的四周
                let queue = []
                let sum = 0
                let m = grid.length
                let n = grid[0].length
                for (let i = 0; i < m; i++) {
                    for (let j = 0; j < n; j++) {
                        if (grid[i][j] == "1") {
                            grid[i][j] = 0
                            sum++
                            queue.push([i, j])
                            bfs(queue, grid)
                        }
                    }
                }
                return sum
                function bfs(queue, grid) {
                    //逐个出栈
                    const dirs = [
                        [0, 1],
                        [0, -1],
                        [1, 0],
                        [-1, 0],
                    ]
                    while (queue.length) {
                        const cur = queue.pop()
                        //判断它的四周
                        for (const dir of dirs) {
                            let x = cur[0] + dir[0]
                            let y = cur[1] + dir[1]
                            //找出四周
                            if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == "0") {
                                continue
                            }
                            grid[x][y] = "0"
                            queue.push([x, y])
                        }
                    }
                }
            }
        </script>
    </body>
</html>
